/*
 * @Author: liuqiang
 * @Date: 2021-02-08 10:00:10
 * @Last Modified by: liuqiang
 * @Last Modified time: 2021-02-20 18:04:07
 */
const { Sequelize, DataTypes, Op } = require('sequelize');
const { logger } = require('../utils/log');
const { doSqlMiddle } = require('../utils/tool');

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: './server/storage/customers.sqlite',
  logging: (msg) => {
    logger.info(msg);
  },
});

const Customer = sequelize.define('Customer', {
  no: {
    // 会员号
    type: DataTypes.INTEGER,
    unique: true,
    autoIncrement: true,
    primaryKey: true,
  },
  id: {
    // id 唯一
    type: DataTypes.UUID,
    defaultValue: Sequelize.UUIDV1,
    unique: true,
  },
  name: {
    // 客户姓名
    type: DataTypes.STRING,
    allowNull: false,
  },
  phone: {
    // 客户电话
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
  },
  sex: {
    // 客户性别 0 男生 1 女生
    type: DataTypes.NUMBER,
    defaultValue: -1,
  },
  count: {
    // 客户余额
    type: DataTypes.NUMBER,
    allowNull: false,
    defaultValue: 0,
  },
  vip: {
    // vip等级
    type: DataTypes.NUMBER,
    defaultValue: 0,
  },
  pay: {
    // 消费次数
    type: DataTypes.NUMBER,
    defaultValue: 0,
  },
  remark: {
    // 客户备注
    type: DataTypes.TEXT,
  },
});

/*
 * 新建用户
 * name string 用户名
 * phone string 电话
 */
async function createCustomer({ name, phone }) {
  return doSqlMiddle(async () => {
    let customer = await Customer.create({
      name: name,
      phone: phone,
    });
    return customer.toJSON();
  });
}

/*
 * 查询客户
 * limit number 每页个数
 * page number 第几页
 * id string 客户id
 * name string 客户姓名
 * phone string 客户电话
 */
async function findCustomer({ limit, page, id, name, phone }) {
  const query = {
    where: {},
  };
  if (limit) {
    query.limit = limit;
  }
  if (page) {
    query.offset = page * limit;
  }
  if (name) {
    query.where.name = {
      [Op.like]: `%${name}%`, // 模糊匹配姓名
    };
  }
  if (phone) {
    query.where.phone = phone;
  }
  if (id) {
    query.where.id = id;
  }

  if (Object.keys(query.where).length <= 0) {
    delete query.where;
  }

  return doSqlMiddle(async () => {
    let customer = await Customer.findAll(query);
    return customer.map((item) => item.dataValues);
  });
}

// 更新用户资料
const canUpdateField = {
  name: true,
  phone: true,
  sex: true,
  count: true,
  vip: true,
  pay: true,
  remark: true,
};
async function updateCustomer(data) {
  let newData = {};
  for (let key in data) {
    if (canUpdateField[key]) {
      newData[key] = data[key];
    }
  }
  return doSqlMiddle(async () => {
    await Customer.update(newData, {
      where: {
        id: data.id,
      },
      returning: true,
    });
    const user = await findCustomer({ id: data.id });
    return user.length > 0 ? user[0] : {};
  });
}

module.exports = {
  Customer,
  sequelize,
  createCustomer,
  findCustomer,
  updateCustomer,
};
